package com.woniuxy.qiantai.utils;

import com.woniuxy.qiantai.entity.Book;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class CookieUtils {
    //把cookie写到客户端
    public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, Boolean isDelete) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath("/");
        if (isDelete) {
            cookie.setMaxAge(0);//设置cookie的时间为0 等于删除了cookie
        }
        response.addCookie(cookie);
    }
    //从cookies中获取指定cookie的值
    public  static  String getCookieValueByName(HttpServletRequest request,String cookieName){
        //从请求中获取全部的cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(),cookieName)){
            return  cookie.getValue();
            }
        }
        return  null;
    }
    //将Jwt的token 存入cookie中
    public  static  void setUserToken2Cookie(HttpServletResponse response, String token){
        addCookie(response,"user_token",token,false);
    }
    //从cookie中取出token
    public static  String getUserToken2Cookie(HttpServletRequest request){
        return getCookieValueByName(request, "user_token");
    }
    //删除cookie中指定的cookie
    public  static  void deleteUserTokenFromCookie(HttpServletResponse response){
        addCookie(response,"user_token",null,true);
    }
}

